#!/bin/bash

# 设置ES集群地址和认证信息
ES_HOST="10.10.51.89"
ES_PORT="9200"
ES_USER="your_es_user"
ES_PASSWORD="your_es_password"

# 设置Snapshot仓库名称和备份目录
REPO_NAME="sumz_repo"
BACKUP_DIR="/usr/share/elasticsearch/data"

# 创建Snapshot仓库
create_snapshot_repository() {
    curl -X PUT -u "$ES_USER:$ES_PASSWORD" "http://$ES_HOST:$ES_PORT/_snapshot/$REPO_NAME" -H 'Content-Type: application/json' -d '{
      "type": "fs",
      "settings": {
        "location": "'$BACKUP_DIR'",
        "compress": true
      }
    }'
}

# 创建Snapshot
create_snapshot() {
    local SNAPSHOT_NAME="snapshot_$(date +'%Y%m%d%H%M%S')"
    curl -X PUT -u "$ES_USER:$ES_PASSWORD" "http://$ES_HOST:$ES_PORT/_snapshot/$REPO_NAME/$SNAPSHOT_NAME?wait_for_completion=true"
}

# 查看所有Snapshot
list_snapshots() {
    curl -X GET -u "$ES_USER:$ES_PASSWORD" "http://$ES_HOST:$ES_PORT/_cat/snapshots/$REPO_NAME?v"
}

# 备份ES数据库
backup_es_database() {
    create_snapshot_repository
    create_snapshot
    list_snapshots
}

# 调用备份ES数据库方法
backup_es_database